package com.zl.learning.db.redis;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.concurrent.TimeUnit;

public class TestRedis3 {
    private JedisPool jedisPool = init();

    private JedisPool init() {
        JedisPoolConfig config = new JedisPoolConfig();
//        return new JedisPool(config, "localhost", 6379);
        return new JedisPool(config, "172.31.4.247", 6379);
    }

    public Jedis getJedis() {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
        } catch (Exception e) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            return getJedis();
        }
        return jedis;
    }

    @Test
    public void test1() {
        Jedis jedis = getJedis();
        try {
            for (int i = 0; i < 100; i++) {
                try {
                    jedis.set("key_" + i, "val_" + i);
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    jedis = getJedis();
                }
            }
        } catch (Exception e) {
            jedis = getJedis();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    @Test
    public void test2() {
        try (Jedis jedis = jedisPool.getResource()){
            jedis.set("name","zhangsan");
            System.out.println(jedis.get("name"));
        }
    }
}
